/*
 * @Date: 2023-08-04 14:16:04
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-04 15:43:13
 * @FilePath: \mt-middleware-server\src\filters\http-exception\http-exception.filter.ts
 * @Description:
 */
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Inject,
  Logger as nestLogger,
} from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { getReqMainInfo } from 'utils/common/getReqMainInfo';
import { Logger } from 'winston';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const exceptionResponse = exception.getResponse();
    nestLogger.log('错误提示11', exceptionResponse);

    const message =
      (exception?.getResponse() as { message?: any })?.message ?? '';

    nestLogger.log('错误提示', message);
    this.logger.error('HttpExceptionFilter', {
      status: HttpStatus.SERVICE_UNAVAILABLE,
      req: getReqMainInfo(request),
      res: (exception as any)?.response?.data ?? {},
    });
    const errorResponse = {
      isSuccess: false,
      msg: message,
      code: 500, // 自定义code
      url: request.originalUrl, // 错误的url地址
    };
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    // 设置返回的状态码、请求头、发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
